#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
发送客服消息接口
"""

from datetime import datetime
from flask import Blueprint, request, jsonify, current_app
from utils.logger import get_logger

kf_send_msg_bp = Blueprint('kf_send_msg', __name__)
logger = get_logger(__name__)


@kf_send_msg_bp.route('/cgi-bin/kf/send_msg', methods=['POST'])
def send_msg():
    """发送客服消息"""
    try:
        # 获取请求参数
        access_token = request.args.get('access_token')
        
        logger.info("发送客服消息请求")
        
        # 参数验证
        if not access_token:
            logger.warning("缺少access_token参数")
            return jsonify({
                "errcode": 41001,
                "errmsg": "missing access_token parameter"
            }), 400
        
        # 获取请求体
        request_data = request.get_json()
        if not request_data:
            logger.warning("缺少请求体")
            return jsonify({
                "errcode": 41001,
                "errmsg": "missing request body"
            }), 400
        
        open_kfid = request_data.get('open_kfid')
        touser = request_data.get('touser')
        msgtype = request_data.get('msgtype')
        msgid = request_data.get('msgid')
        
        logger.info(f"发送消息 - 客服账号: {open_kfid}, 用户: {touser}, 类型: {msgtype}")
        
        # 参数验证
        if not open_kfid or not touser or not msgtype:
            logger.warning("缺少必要参数")
            return jsonify({
                "errcode": 41001,
                "errmsg": "missing required parameters"
            }), 400
        
        # 获取数据管理器
        data_manager = current_app.data_manager
        
        # Mock版本：跳过严格的验证，直接处理消息
        logger.info("Mock模式：跳过token和会话状态验证")
        
        # 自动创建会话（如果不存在），收到消息时更新活动时间
        session = data_manager.get_session(touser, open_kfid, update_activity=True)
        if not session:
            logger.info(f"自动创建会话 - 用户: {touser}, 客服: {open_kfid}")
            session_data = {
                "external_userid": touser,
                "open_kfid": open_kfid,
                "service_state": 1,  # 默认状态
                "servicer_userid": "mock_servicer_001",
                "create_time": int(datetime.now().timestamp())
            }
            data_manager.update_session(touser, open_kfid, session_data)
        
        # 生成消息ID
        if not msgid:
            msgid = f"mock_msg_{int(datetime.now().timestamp())}"
        
        # 创建消息记录
        message = {
            "msgid": msgid,
            "open_kfid": open_kfid,
            "external_userid": touser,
            "send_time": int(datetime.now().timestamp()),
            "msgtype": msgtype,
            "direction": "send"  # 发送方向
        }
        
        # 根据消息类型添加内容
        if msgtype == "text":
            message["text"] = request_data.get("text", {})
        elif msgtype == "image":
            message["image"] = request_data.get("image", {})
        elif msgtype == "voice":
            message["voice"] = request_data.get("voice", {})
        elif msgtype == "file":
            message["file"] = request_data.get("file", {})
        elif msgtype == "link":
            message["link"] = request_data.get("link", {})
        elif msgtype == "miniprogram":
            message["miniprogram"] = request_data.get("miniprogram", {})
        
        # 保存消息
        data_manager.add_message(message)
        
        # 更新统计信息
        data_manager.update_stats(success=True)
        
        logger.info(f"消息发送成功 - 消息ID: {msgid}")
        
        return jsonify({
            "errcode": 0,
            "errmsg": "ok",
            "msgid": msgid
        })
        
    except Exception as e:
        logger.error(f"发送客服消息失败: {e}")
        data_manager = current_app.data_manager
        data_manager.update_stats(success=False)
        
        return jsonify({
            "errcode": 500,
            "errmsg": "internal error"
        }), 500


def _validate_message_type(msgtype, request_data):
    """验证消息类型和内容"""
    valid_types = ["text", "image", "voice", "file", "link", "miniprogram"]
    
    if msgtype not in valid_types:
        return False
    
    # 检查对应类型的必要字段
    if msgtype == "text":
        return "text" in request_data and "content" in request_data["text"]
    elif msgtype == "image":
        return "image" in request_data and "media_id" in request_data["image"]
    elif msgtype == "voice":
        return "voice" in request_data and "media_id" in request_data["voice"]
    elif msgtype == "file":
        return "file" in request_data and "media_id" in request_data["file"]
    elif msgtype == "link":
        link = request_data.get("link", {})
        return all(key in link for key in ["title", "desc", "url"])
    elif msgtype == "miniprogram":
        miniprogram = request_data.get("miniprogram", {})
        return all(key in miniprogram for key in ["title", "pagepath", "thumb_media_id"])
    
    return True
